<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :span="7">
                <a-form-item label="数据来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    allow-clear
                    placeholder="请选择数据来源"
                    v-model="selectedCheckTypes"
                    mode="multiple"
                    @change="handleCheckTypeChange"
                    style="height: 40px; overflow-y: auto"
                  >
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="item in CheckTypeList" :key="item.id" :value="item.item">{{
                      item.item
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item label="检查时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    @change="onChange1"
                    :style="{ width: '50%' }"
                    v-model="TimeOn"
                  />
                  <a-date-picker
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    @change="onChange2"
                    :style="{ width: '50%' }"
                    v-model="TimeEnd"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item label="隐患单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    allowClear
                    showSearch
                    style="scroll: true"
                    tree-node-filter-prop="title"
                    v-model="queryParam.DangerOrganizationName"
                    :treeData="QHSEOrganizationTree"
                    v-if="QHSEOrganizationTree.length"
                    @change="onChangeDangerData"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择隐患单位"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="48" >
              <a-col :span="7">
                <a-form-item label="隐患级别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    v-model="selectedDangerType"
                    allow-clear
                    mode="multiple"
                    placeholder="请选择隐患级别"
                    style="height: 40px; overflow-y: auto;"
                    @change="handleDangerType">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="(item) in HazardLevelList" :key="item.id" :value="item.item" >{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item label="作业专业" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    allow-clear
                    placeholder="请选择作业专业"
                    style="height: 40px; overflow-y: auto"
                    v-model="selectedWorkSpecialty"
                    @change="handleZYZYSelectChange"
                  >
                    <a-select-option
                      v-for="item in QHSEKeyWorkSpecialtyList"
                      :key="item.id"
                      :value="item.specialty"
                      :code="item.specialtyCode"
                    >{{ item.specialty }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="7" class="search-buttons">
                <a-button type="primary" @click="handleClick" v-if="hasPerm('hdv_qhse_d_zgqk')">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-card :bordered="false">
        <a-col>
          <span style="font-weight:bold">隐患数量：</span><span v-text="DangerCount" style="color:rgb(227, 227, 70);font-weight:bolder;font-size:18px;margin-right:20px"></span>
          <span style="font-weight:bold">已整改：</span><span v-text="DangerRectified" style="color:rgb(56, 158, 13);font-weight:bolder;font-size:18px;margin-right:20px"></span>
          <span style="font-weight:bold">未整改：</span><span v-text="DangerRectification" style="color:red;font-weight:bolder;font-size:18px;"></span>
        </a-col>
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :alert="null"
          :rowKey="(record) => record.qhseXyDangerId"
          :rowSelection="null"
          bordered
        >
          <span slot="action" slot-scope="text, record">
            <a-button size="small" style="color:#389e0d;background-color: #f6ffed;border-color: #b7eb8f;">
              <a @click="$refs.detail.edit(record)">
                <a-icon type="file-text" /> 详情
              </a>
            </a-button>
          </span>
        </s-table>
        <dan-detail ref="detail" @ok="handleOk" />
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import { STable, XCard, XDown, DanDetail } from '@/components'
import { Empty } from 'ant-design-vue'
import { getQHSECheckTypeList } from '@/api/modular/system/QHSEHazardQuery'
import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
import { getQHSEHazardLevelList, getQHSEHazardStatusList } from '@/api/modular/system/QHSEDictionary'
import { getQHSEKeyWorkSpecialtyList } from '@/api/modular/system/QHSEKeyWork'
import { danReformation } from '@/api/modular/system/QHSEDanger'
import moment from 'moment'
import { mapGetters } from 'vuex'
export default {
  components: {
    XDown,
    XCard,
    STable,
    DanDetail
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 查询参数
      TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
      TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
      // 表头
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '检查日期',
          dataIndex: 'CheckDate',
          customRender: (text, record) => {
            if (record.CheckDate) {
              const dateParts = record.CheckDate.split('T')[0].split('-')
              return `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`
            }
            return ''
          }
        },
        {
          title: '检查人员',
          dataIndex: 'CheckName'
        },
        {
          title: '隐患单位',
          dataIndex: 'OrganizationName'
        },
        {
          title: '隐患区域',
          dataIndex: 'Location'
        },
        {
          title: '隐患性质',
          dataIndex: 'DangerType',
          customRender: function (text) {
            if (text === '重大隐患') {
              return <span style={{ color: 'red' }}>{text}</span>
            } else if (text === '较大隐患') {
              return <span style={{ color: 'orange' }}>{text}</span>
            } else {
              return <span style={{ color: 'rgb(227, 227, 70)' }}>{text}</span>
            }
          }
        },
        {
          title: '隐患状态',
          dataIndex: 'Status',
          customRender: function (text) {
            if (text === '已整改') {
              return <span style={{ color: 'rgb(34, 173, 34)' }}>{text}</span>
            } else {
              return <span style={{ color: 'red' }}>{text}</span>
            }
          }
        },
        {
          title: '作业项目',
          dataIndex: 'WorkItem'
        },
        {
          title: '隐患描述',
          dataIndex: 'Description',
          customRender: (text) => (
            <a-tooltip title={text}>{text.length > 5 ? text.substr(0, 5) + '...' : text}</a-tooltip>
          )
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return danReformation(Object.assign(parameter, this.queryParam)).then((res) => {
          const newRes = {}
          newRes.rows = res.result.Rows
          newRes.totalPage = res.result.TotalPage
          newRes.totalRows = res.result.TotalRows
          newRes.pageNo = res.result.PageNo
          newRes.pageSize = res.result.PageSize
          this.DangerCount = res.DangerCount
          this.DangerRectification = res.DangerRectification
          this.DangerRectified = res.DangerRectified
          return newRes
        })
      },
      queryParam: {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
      },
      selectedKeys: [],
      selectedCheckTypes: [],
      selectedDangerType: [],
      selectedWorkSpecialty: [],
      QHSEKeyWorkSpecialtyList: [],
      CheckTypeList: [],
      // selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      QHSEOrganizationTree: [],
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'workflowId',
        value: 'id',
        parentId: 'parentId'
      },
      HazardLevelList: [],
      HazardStatusList: [],
      DangerCount: 0,
      DangerRectification: 0,
      DangerRectified: 0,
      secondOraName: {
          id: ''
        }
    }
  },
  created() {
    this.getQHSEOrganizationTree()
    this.getQHSEKeyWorkSpecialtyList()
    this.getQHSEHazardLevelList()
    this.getQHSEHazardStatusList()
    this.getQHSECheckTypeList()
    this.columns.push({
      title: '操作',
      width: '150px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    })
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    handleClick() {
      if ((!this.TimeOn && !this.TimeEnd) || (this.TimeOn && this.TimeEnd)) {
        this.$refs.table.refresh(true)
      } else {
        // 提示用户需要填写完整的时间信息
        this.$message.warning('请填写完整的时间信息')
      }
    },
    onChange1(date, dateString) {
      console.log(dateString, date)
      if (this.queryParam.TimeEnd && dateString) {
        if (dateString > this.queryParam.TimeEnd) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD')
        } else {
          this.queryParam.TimeOn = dateString
        }
      } else {
        this.queryParam.TimeOn = dateString
      }
    },
    onChange2(date, dateString) {
      if (this.queryParam.TimeOn && dateString) {
        if (this.queryParam.TimeOn > dateString) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
        }
      } else {
        this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
      }
    },
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
      this.treeLoading = false
      if (!res.success) {
          return
      }
      this.QHSEOrganizationTree = res.data
      if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
     })
    },
    getQHSEKeyWorkSpecialtyList(text) {
      getQHSEKeyWorkSpecialtyList().then((res) => {
        this.QHSEKeyWorkSpecialtyList = res.data
       })
    },
    getQHSEHazardLevelList(text) {
      getQHSEHazardLevelList().then((res) => {
        this.HazardLevelList = res.data
      })
    },
    getQHSEHazardStatusList(text) {
      getQHSEHazardStatusList().then((res) => {
        this.HazardStatusList = res.data
      })
    },
    getQHSECheckTypeList(text) {
      getQHSECheckTypeList().then((res) => {
        this.CheckTypeList = res.data // 将后端返回的数据赋值给 CheckTypeList
        //  console.log(this.CheckTypeList)
      })
    },
    onChangeDangerData(value, label, extra) {
      // console.log(value, label, extra)
      if (extra.triggerNode === undefined) {
        this.queryParam.DangerOrganizationName = null
        this.queryParam.DangerOrganizationId = null
      } else {
        this.queryParam.DangerOrganizationName = extra.triggerNode._props.title
        this.queryParam.DangerOrganizationId = extra.triggerNode._props.value
      }
    },
    handleCheckTypeChange(value) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.selectedCheckTypes = this.CheckTypeList.map((item) => item.item)
      }
      this.queryParam.CheckTypes = this.selectedCheckTypes.map((option) => option.toString())
    },
    handleDangerType(value) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.selectedDangerType = this.HazardLevelList.map(item => item.item)
      } // 取消选中全部选项，更新 selectedCheckTypes
        this.queryParam.dangerTypes = [...this.selectedDangerType]
    },
    handleZYZYSelectChange(value, option) {
      if (option) {
        if (value.includes('全部')) {
          this.selectedWorkSpecialty = this.QHSEKeyWorkSpecialtyList.map(item => item.specialty)
        }
      }
      this.queryParam.workSpecialty = [...this.selectedWorkSpecialty]
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    reset() {
      this.selectedCheckTypes = []
      this.selectedDangerType = []
      this.selectedWorkSpecialty = []
      this.queryParam = {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD')
      }
      this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
      this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
    }
  }
}
</script>
<style lang="less" scoped>
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
}
</style>
